package com.mfh.auto.create.mvvm.autocreatemvvm.file.hm

import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile

/**
 * 常量修改类
 */
object ConstantEdit {

    /**
     * 添加内容
     */
    fun addConstant(directory: PsiDirectory, data: String) {
        findConstantFile(directory)?.let { file ->
            // 获取文档管理器和文档
            val documentManager = PsiDocumentManager.getInstance(file.project)
            val document = documentManager.getDocument(file) ?: return

            val lastIndexOf = document.text.lastIndexOf("}")
            if (lastIndexOf > 0) {
                document.insertString(lastIndexOf - 1, "\n${data}\n")
            } else {
                document.insertString(document.textLength - 1, "\n${data}\n")
            }

            // 提交更改
            documentManager.commitDocument(document)
        }
    }

    /**
     * 获取常量文件
     */
    private fun findConstantFile(directory: PsiDirectory): PsiFile? {
        var dir: PsiDirectory? = directory
        var result: PsiFile? = null
        while (dir?.parent != null && result == null) {
            dir = dir.parent
            result = dir?.findSubdirectory("library")
                ?.findSubdirectory("src")
                ?.findSubdirectory("main")
                ?.findSubdirectory("ets")
                ?.findSubdirectory("constant")
                ?.findFile("RouterPathConstant.ets")
        }
        return result
    }


}